<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 2018/10/13
 * Time: 11:41
 */

namespace app\common\model;


use think\Db;
use think\Exception;

class Config extends BaseModel
{
    protected $deleteTime = false;
    /**
     * 获取配置列表
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public static function getList() {
        return self::paginate(input('param.limit', 15));
    }

    /**
     * 创建或者编辑配置
     * @param $data
     * @param int $id
     * @return \think\response\Json
     */
    public static function createOrUpdateConfig($data, $id = 0) {
        Db::startTrans();
        try {
            if ($id > 0) {
                if (!$data['value']) {
                    throw new Exception('请填写配置的value');
                }
                $config = self::get(['id' => $id]);
                if (!$config) {
                    throw new Exception('配置不存在');
                }
                $check_config_login = self::where('key', '=', $data['key'])
                    ->where('id', 'neq', $id)
                    ->find();
                if ($check_config_login) {
                    throw new Exception('配置key已存在');
                }

                $config->save(['value' => $data['value']]); // 更新用户信息,只写入数据表有的字段（对象写法）

            } else {
                if (!$data['key'] || !$data['value']) {
                    throw new Exception('请填写配置的key和value');
                }

                $check_config_key = self::where('key', '=', $data['key'])->find();
                if ($check_config_key) {
                    throw new Exception('配置key已存在');
                }
                self::create($data, true);// 创建用户信息,只写入数据表有的字段（静态写法）
            }
            Db::commit();
            return return_data('保存成功！');
        } catch (Exception $e) {
            Db::rollback();
            return return_data($e->getMessage(), 1);
        }
    }

    /**
     * 根据key获取配置的值
     * @param $key
     * @return mixed
     */
    public static function getConfigValue($key) {
        return self::where('key', '=', $key)->value('value');
    }

    /**
     * 获取网站配置项
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getWebConfig() {
        $data = self::where('key', 'like', 'web_%')->select();
        $web_config = [];
        foreach ($data as $v) {
            $web_config[$v->key] = $v->value;
        }
        return $web_config;
    }
}